"use client";

import {Button, Image} from "@nextui-org/react";
import React, { useState, useRef, useEffect, useCallback } from 'react';


const DisplayFunctionViewer: React.FC<{ title: string; desc: string }> = ({ title, desc }) => {
  return (
    <div className="h-lvh flex flex-col items-center content-center justify-items-center justify-center">
      <h1 className="text-5xl  font-semibold text-center leading-normal px-40">{title}</h1>
      <p className="mt-10 text-gray-500 text-center leading-normal px-28">{desc}</p>
    </div>
  );
};


export default function DisplayFunction() {

  const functions = [
    {
      id: 1,
      title: '项目管理',
      icon:'f-1.png',
      pic: 'df-1.gif',
      template: [
        <DisplayFunctionViewer 
          title="丰富模板一键复用" 
          desc="提供 40+ 项目模板最佳实践，一键复用"
          key="1-1"
        />, 
        <DisplayFunctionViewer 
          title="随时随地知晓信息" 
          desc="多种视图，按需切换「谁」在「何时」「做什么」一目了然"
          key="1-2"

        />,
        <DisplayFunctionViewer 
          title="任务跟踪有始有终" 
          desc="任务分配至人，支持自定义设置实现有始有终的闭环管理"
          key="1-3"

        />,
        <DisplayFunctionViewer 
          title="统计分析把控全局" 
          desc="汇总项目和成员数据随时掌控进展"
          key="1-4"
        />
      ]
    }, {
      id: 2,
      title: '轻任务协同',
      icon:'f-2.png',
      pic: 'df-2.gif',
      template: [
        <DisplayFunctionViewer 
          title="我的任务更低门槛" 
          desc="个人专属任务大盘让协作更加轻量"
          key="2-1"
        />,
      ]
    }, {
      id: 3,
      title: '一站式体验',
      icon:'f-3.png',
      pic: 'df-3.gif',
      template: [
        <DisplayFunctionViewer 
          title="打通钉钉群聊" 
          desc="项目关联钉群，成员自动同步进展实时触达，重要消息绝不遗漏"
          key="3-1"
        />,
      ]
    }
  ]

  const sectionRefs = useRef<(HTMLDivElement | null)[]>([]);
  // 使用 useState 管理 curIndex
  const [curIndex, setCurIndex] = useState(0);

   // 滚动到指定的 section
   const scrollToSection = (index: number) => {
    sectionRefs.current[index]?.scrollIntoView({
      behavior: 'smooth',
      block: 'start',
    });
    setCurIndex(index);
  };

  // Intersection Observer 的回调
  const handleIntersection = useCallback(
    (entries: IntersectionObserverEntry[]) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          const visibleIndex = sectionRefs.current.findIndex(
            (ref) => ref === entry.target
          );
          if (visibleIndex !== -1) {
            setCurIndex(visibleIndex);
          }
        }
      });
    },
    []
  );

  // 初始检查当前可见的 section
  const checkVisibleSection = useCallback(() => {
    sectionRefs.current.forEach((section, index) => {
      if (section) {
        const rect = section.getBoundingClientRect();
        if (rect.top >= 0 && rect.top < window.innerHeight / 2) {
          setCurIndex(index);
        }
      }
    });
  }, []);

  useEffect(() => {
    const observer = new IntersectionObserver(handleIntersection, {
      threshold: [0.25, 0.5], // 调整 threshold，让 section 进入视口时触发
    });

    sectionRefs.current.forEach((section) => {
      if (section) {
        observer.observe(section);
      }
    });

    // 初始加载时检查当前可见的 section
    checkVisibleSection();

    return () => {
      observer.disconnect(); // 在组件卸载时移除监听
    };
  }, [handleIntersection, checkVisibleSection]);

  
  return (
    <div>
      <div className='px-40 flex flex-row-reverse mt-16'>
        <div className="w-11/12" style={{height: '1vh', position: 'sticky', top: '120px'}}>
          <div className="flex">
            {functions.map((f, index) => (
              <div className="ml-4">
                <Button 
                  startContent={<Image src={f.icon} style={{width:30}} alt="images"/>}  
                  onClick={() => scrollToSection(index)} 
                  key={f.id} 
                  variant={curIndex === index ? "flat" : "light"}
                  color={curIndex === index ? "primary" : "default"}
                >
                  {f.title}
                </Button>
              </div>
              ))}
          </div>
          <Image src={functions[curIndex].pic} alt="111"  />
        </div>
        <div className="">
          {functions.map((f,index) => (
            <div 
              key={f.id} 
              className="" 
              ref={(el) => {
                sectionRefs.current[index] = el; 
              }}
            >
              {f.template}
              
            </div>
          ))}
        </div>
        
      </div>
    </div>
  )
}